import { Injectable, NotFoundException } from '@nestjs/common';
import { CreateSentenceDto } from './dto/create-sentence.dto';
import { UpdateSentenceDto } from './dto/update-sentence.dto';
import { Repository } from 'typeorm';
import { Sentence } from './entities/sentence.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { format } from 'date-fns';

@Injectable()
export class SentenceService {
  constructor(@InjectRepository(Sentence) private readonly sentenceRepository: Repository<Sentence>) { }

  create(createSentenceDto: CreateSentenceDto) {
    this.sentenceRepository.save(createSentenceDto);
    return createSentenceDto;
  }

  findAll() {
    return `This action returns all sentence`;
  }

  async findRandom() {
    const sentence: Sentence = await this.sentenceRepository
      .createQueryBuilder('sentence')
      .orderBy('RAND()')
      .limit(1)
      .getOne();
    if (!sentence) {
      throw new NotFoundException('No sentence found');
    }
    return {
      ...sentence,
      createdAt: format(new Date(sentence.createdAt), 'yyyy-MM-dd HH:mm:ss'),
      updatedAt: format(new Date(sentence.updatedAt), 'yyyy-MM-dd HH:mm:ss')
    };
  }

  findOne(id: number) {
    return `This action returns a #${id} sentence`;
  }

  update(id: number, updateSentenceDto: UpdateSentenceDto) {
    return `This action updates a #${id} sentence`;
  }

  remove(id: number) {
    return `This action removes a #${id} sentence`;
  }
}
